import 'package:flutter/material.dart';
import 'package:flutter_cjadsdk_plugin/flutter_cjadsdk_plugin.dart';
import 'package:get_storage/get_storage.dart';
import 'package:zhibao_flutter/api/commom/common_view_model.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/data/cache_img.dart';
import 'package:zhibao_flutter/util/data/language.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:zhibao_flutter/widget/base/my_error_widget.dart';
import 'package:zhibao_flutter/widget/image/sw_image.dart';
import 'dart:async';
import 'dart:io';

// import 'package:bugly_crash/bugly.dart';
// import 'package:bugly_crash/buglyLog.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:zhibao_flutter/test/live_log_page.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/config/config_route.dart';
import 'package:zhibao_flutter/util/data/q1_data.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/func/sp_util.dart';
import 'package:zhibao_flutter/util/http/http.dart';
import 'package:zhibao_flutter/zone.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:logging/logging.dart';
import 'package:oktoast/oktoast.dart';

// import 'package:paulonia_cache_image/paulonia_cache_image.dart';
// import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
Logger get q1Logger => Logger.root;

void main() async {
  // runZonedGuarded<Future<Null>>(() async {
  // 如果需要 ensureInitialized，请在这里运行。
  WidgetsFlutterBinding.ensureInitialized();

  /// Init of sp.
  await SpUtil.perInit();

  /// LogShow
  Logger.root.level = Level.ALL; // defaults to Level.INFO
  Logger.root.onRecord.listen((record) {
    final String str =
        '${strNoEmpty(record.message) ? ": " : ""}${record.message}';
    LogUtil.vPrint(str);
    LiveLogPageData.writeData(str);
    LiveLogPageData.writeData("\n");
  });

  /// Set Environment
  Environment.setCurrent(EnvironmentType.pro);

  /// Show test menu when open app?
  AppConfig.showTestMenu = true;

  const SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
    // Status bar color set for transparent.
    statusBarColor: Colors.transparent,

    /// Brightness.light = Status bar text Color（White）
    statusBarIconBrightness: Brightness.dark, // Status bar text Color（Black）
  );
  SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

  /// Set only allow vertical screen in the app.
  if (!kIsWeb) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }
  // SwImageData init.
  SwImageData.initData();

  /// Init the storage.
  GetStorage.init();

  /// Init local data.
  await Q1Data.init();

  /// WebView Option
  try {
    if (Platform.isAndroid) {
      await InAppWebViewController.setWebContentsDebuggingEnabled(true);

      var swAvailable = await WebViewFeature.isFeatureSupported(
          WebViewFeature.SERVICE_WORKER_BASIC_USAGE);
      var swInterceptAvailable = await WebViewFeature.isFeatureSupported(
          WebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);

      if (swAvailable && swInterceptAvailable) {
        ServiceWorkerController serviceWorkerController =
            ServiceWorkerController.instance();

        await serviceWorkerController
            .setServiceWorkerClient(ServiceWorkerClient(
          shouldInterceptRequest: (request) async {
            print(request);
            return null;
          },
        ));
      }
    }
  } catch (e) {
    LogUtil.d("Init webview error:::${e.toString()}");
  }

  //一、这里配置上报APP未捕获到的异常，业务可以自由决定上报的信息
  FlutterError.onError = (FlutterErrorDetails details) async {
    print("zone current print error");
    Zone.current.handleUncaughtError(
        details.exception, details.stack ?? StackTrace.empty);
  };

  /// Custom error widget.
  ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
    return MyErrorWidget();
  };

  // Splash ad.
  unawaited(adHandle());

  // runZonedGuarded(() {
  runApp(const MyApp());
  // }, (Object error, StackTrace stack) {
  //   LogUtil.d(
  //       "runZonedGuarded::error=${error.toString()};stack=${stack.toString()}");
  // });
}

Future adHandle() async {
  // Ad init.
  if (!kIsWeb) {
    FlutterCjadsdkPlugin.init(() async {
      print("FlutterCjadsdkPlugin::success");
      await Future.delayed(const Duration(milliseconds: 600));
      // Splash ad.
      // Cancel splash ad on Apr 21 2024.
      // await FlutterCjadsdkPlugin.getSplashAdMethod();
    });
    await FlutterCjadsdkPlugin.adSdkSetup();
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    AppConfig.currentLan.value = AppConfig.locale;
    super.initState();

    /// 在设置页面的【账号信息】点击10次也会出来。
    // if (AppConfig.showTestMenu) {
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   /// 显示测试菜单
    //   TestMenu.showOverlayEntry(context);
    // });
    // }
  }

  @override
  Widget build(BuildContext context) {
    SwImageData.cacheImgDataOfNetWork(context);

    /// 加载缓存图片
    cacheImgData(context);
    return OKToast(
      dismissOtherOnShow: true,
      child: GetMaterialApp(
        debugShowCheckedModeBanner: false,
        supportedLocales: LanguageUtil.supportedLocales,
        translations: AppTranslations(),
        locale: AppConfig.locale,
        fallbackLocale: AppConfig.defLan,
        localizationsDelegates: [
          GlobalCupertinoLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate
        ],
        theme: MyTheme.theme(),
        title: AppConfig.appName,
        getPages: RouteConfig.getPages,
        defaultTransition: Transition.cupertino,
        initialRoute:
            Q1Data.isLogin ? RouteConfig.mainPage : RouteConfig.loginPage,
        builder: (context, child) => GestureDetector(
          onTap: () {
            hideKeyboard(context);
          },
          child: child,
        ),
      ),
    );
  }

  void hideKeyboard(BuildContext context) {
    final FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
